package com.ruoyi.web.controller.miniapp;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginByTelephoneBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDataInfo;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.retirement.domain.*;
import com.ruoyi.retirement.service.*;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 小程序接口
 * @author 曹旭
 * @date 2025-09-04
 */
@RestController
@RequestMapping("/miniApp")
public class MiniAppCommonController extends BaseController
{
    @Autowired
    private IRetirementArticleService retirementArticleService;

    @Autowired
    private IRetirementCarouselService retirementCarouselService;

    @Autowired
    private IRetirementMenuService retirementMenuService;

    @Autowired
    private IRetirementClassifyTwoService retirementClassifyTwoService;

    @Autowired
    private IRetirementArticleCollectRecordService retirementArticleCollectRecordService;

    @Autowired
    private IRetirementArticleCollectService retirementArticleCollectService;

    @Autowired
    private IRetirementArticleEnrollService retirementArticleEnrollService;

    @Autowired
    private ISysUserService userService;


    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    /**
     * 轮播图
     */
    @PostMapping(value = "/carousel")
    public AjaxResult carousel()
    {
        List<RetirementCarousel> list = retirementCarouselService.selectRetirementCarouselList(new RetirementCarousel());
        return success(list);
    }

    /**
     * 菜单一级分类列表
     */
    @PostMapping(value = "/menuList")
    public AjaxResult menuList(RetirementMenu retirementMenu)
    {
        List<RetirementMenu> onelist = retirementMenuService.selectRetirementMenuList(retirementMenu);
        List<RetirementClassifyTwo> twolist = retirementClassifyTwoService.selectRetirementClassifyTwoList(new RetirementClassifyTwo());
        //为每个一级分类设置子分类
        for (RetirementMenu menu : onelist) {
            List<String> subCategories = twolist.stream()
                    .filter(two -> two.getLevelOneId() != null && two.getLevelOneId().equals(menu.getId()))
                    .map(RetirementClassifyTwo::getName)
                    .collect(Collectors.toList());
            menu.setSubCategories(subCategories);
        }
        return success(onelist);
    }


    /**
     * 获取文章详细信息
     */
    @GetMapping(value = "/getDetail")
    public AjaxResult getInfo(Long id)
    {
        //查询文章详情
        RetirementArticle retirementArticle = retirementArticleService.selectRetirementArticleById(id);
        return success(retirementArticle);
    }


    /**
     * 根据当前用户部门获取文章列表
     */
    @GetMapping(value = "/getArticleList")
    public PageDataInfo getArticleList(RetirementArticle retirementArticle)
    {
        if (!isAdmin()){
            retirementArticle.setDept(SecurityUtils.getLoginUser().getDeptId().toString());
        }
        // 获取分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        startPage();
        List<RetirementArticle> list = retirementArticleService.selectRetirementArticleListMiniApp(retirementArticle);
        // 使用扩展的分页信息
        return new PageDataInfo(list, new PageInfo(list).getTotal(), pageNum, pageSize);
    }

    /**
     * 根据当前用户部门获取文章列表 不分页
     */
    @GetMapping(value = "/getArticleListNoPage")
    public AjaxResult getArticleListNoPage(RetirementArticle retirementArticle)
    {
        if (!isAdmin()){
            retirementArticle.setDept(SecurityUtils.getLoginUser().getDeptId().toString());
        }
        List<RetirementArticle> list = retirementArticleService.selectRetirementArticleListMiniApp(retirementArticle);
        // 使用扩展的分页信息
        return AjaxResult.success(list);
    }


    /**
     * 根据id查询文章详细信息
     */
    @GetMapping(value = "/getArticleInfo")
    public AjaxResult getArticleInfo(Long id)
    {
        //文章详情
        RetirementArticle retirementArticle = retirementArticleService.selectRetirementArticleById(id);
        //如果是活动类型 根据文章id 跟 用户id 查询 是否报名
        if ("activity".equals(retirementArticle.getType())){
            RetirementArticleCollect rac = new RetirementArticleCollect();
            rac.setArticleId(id);
            rac.setUserId(SecurityUtils.getLoginUser().getUserId());
            List<RetirementArticleCollect> list = retirementArticleCollectService.selectRetirementArticleCollectList(rac);
            //报名了为 signed
            if (list != null && !list.isEmpty()) {
                retirementArticle.setSignupStatus("signed");
            } else {
                retirementArticle.setSignupStatus("");
            }
        }
        //查询当前用户是否收藏这条文章
        RetirementArticleEnroll retirementArticleEnroll = new RetirementArticleEnroll();
        retirementArticleEnroll.setArticleId(id);
        retirementArticleEnroll.setUserId(SecurityUtils.getLoginUser().getUserId());
        List<RetirementArticleEnroll> raList = retirementArticleEnrollService.selectRetirementArticleEnrollList(retirementArticleEnroll);
        if (raList != null && !raList.isEmpty()) {
            retirementArticle.setCollected(true);
        } else {
            retirementArticle.setCollected(false);
        }
        return success(retirementArticle);
    }

    /**
     *  报名
     */
    @PostMapping(value = "/registration")
    public AjaxResult registration(@RequestBody RetirementArticleCollectRecord retirementArticleCollectRecord)
    {
        RetirementArticle retirementArticle = retirementArticleService.selectRetirementArticleById(retirementArticleCollectRecord.getArticleId());
        //判断是否过了截止日期
        if (retirementArticle!=null && retirementArticle.getDeadline() != null && !retirementArticle.getDeadline().isEmpty()) {
            //截止日期
            String deadline = retirementArticle.getDeadline();
            //当前日期
            String time = DateUtils.getTime();
            if (time.compareTo(deadline) > 0) {
                return error("很抱歉,报名已截止!");
            }
        }else{
            return error("报名失败,请联系管理员");
        }
        RetirementArticleCollect retirementArticleCollect = new RetirementArticleCollect();
        retirementArticleCollect.setArticleId(retirementArticleCollectRecord.getArticleId());
        retirementArticleCollect.setName(retirementArticleCollectRecord.getName());
        retirementArticleCollect.setUserId(SecurityUtils.getLoginUser().getUserId());
        retirementArticleCollect.setPhone(retirementArticleCollectRecord.getPhone());
        retirementArticleCollect.setDate(DateUtils.getTime());
        //报名列表
        retirementArticleCollectService.insertRetirementArticleCollect(retirementArticleCollect);

        //报名历史记录表
        retirementArticleCollectRecord.setDate(DateUtils.getTime());
        //1报名  0取消
        retirementArticleCollectRecord.setStatus("1");
        retirementArticleCollectRecord.setUserId(SecurityUtils.getLoginUser().getUserId());
        retirementArticleCollectRecordService.insertRetirementArticleCollectRecord(retirementArticleCollectRecord);
        return success();
    }


    /**
     *  取消报名
     */
    @PostMapping(value = "/cancelRegistration")
    public AjaxResult cancelRegistration(@RequestBody RetirementArticleCollectRecord retirementArticleCollectRecord)
    {
        //判断报名是否截止
        RetirementArticle retirementArticle = retirementArticleService.selectRetirementArticleById(retirementArticleCollectRecord.getArticleId());
        if (retirementArticle!=null && retirementArticle.getDeadline() != null && !retirementArticle.getDeadline().isEmpty()) {
            //截止日期
            String deadline = retirementArticle.getDeadline();
            //当前日期
            String time = DateUtils.getTime();
            if (time.compareTo(deadline) > 0) {
                return error("活动已结束!");
            }
        }else{
            return error("无法取消,请联系管理员！");
        }

        //删除报名列表信息
        RetirementArticleCollect retirementArticleCollect = new RetirementArticleCollect();
        retirementArticleCollect.setArticleId(retirementArticleCollectRecord.getArticleId());
        retirementArticleCollect.setUserId(SecurityUtils.getLoginUser().getUserId());
        retirementArticleCollectService.deleteRetirementArticleCollectById(retirementArticleCollect);

        //报名历史记录表
        retirementArticleCollectRecord.setDate(DateUtils.getTime());
        //1报名  0取消
        retirementArticleCollectRecord.setStatus("0");
        retirementArticleCollectRecord.setUserId(SecurityUtils.getLoginUser().getUserId());
        retirementArticleCollectRecordService.insertRetirementArticleCollectRecord(retirementArticleCollectRecord);
        return success();
    }


    /**
     *  收藏
     */
    @PostMapping(value = "/collect")
    public AjaxResult collect(@RequestBody RetirementArticleEnroll retirementArticleEnroll)
    {
        if (retirementArticleEnroll!= null && retirementArticleEnroll.getArticleId() != null) {
            retirementArticleEnroll.setUserId(SecurityUtils.getLoginUser().getUserId());
            List<RetirementArticleEnroll> retirementArticleEnrolls = retirementArticleEnrollService.selectRetirementArticleEnrollList(retirementArticleEnroll);
            if (retirementArticleEnrolls.isEmpty()) {
                retirementArticleEnroll.setUserId(SecurityUtils.getLoginUser().getUserId());
                retirementArticleEnroll.setUserName(SecurityUtils.getLoginUser().getUser().getNickName());
                retirementArticleEnroll.setPhone(SecurityUtils.getLoginUser().getUsername());
                retirementArticleEnrollService.insertRetirementArticleEnroll(retirementArticleEnroll);
            }else{
                return error("您已收藏过了");
            }
        }else{
            return error("收藏失败,请联系管理员！");
        }
        return success();
    }

    /**
     *  取消收藏
     */
    @PostMapping(value = "/cancelCollect")
    public AjaxResult cancelCollect(@RequestBody RetirementArticleEnroll retirementArticleEnroll)
    {
        if (retirementArticleEnroll!= null && retirementArticleEnroll.getArticleId() != null) {
            retirementArticleEnroll.setUserId(SecurityUtils.getLoginUser().getUserId());
            retirementArticleEnrollService.deleteRetirementArticleEnrollById(retirementArticleEnroll);
        }else{
            return error("取消收藏失败,请联系管理员！");
        }
        return success();
    }


    /**
     *  我的收藏列表
     */
    @GetMapping(value = "/myCollectList")
    public PageDataInfo myCollectList(RetirementArticle retirementArticle)
    {
        retirementArticle.setUserId(SecurityUtils.getLoginUser().getUserId());
        if (!isAdmin()){
            retirementArticle.setDept(SecurityUtils.getLoginUser().getDeptId().toString());
        }
        // 获取分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        startPage();
        List<RetirementArticle> list = retirementArticleService.selectEnrollList(retirementArticle);
        // 使用扩展的分页信息
        return new PageDataInfo(list, new PageInfo(list).getTotal(), pageNum, pageSize);
    }


    /**
     *  我的报名列表
     */
    @GetMapping(value = "/myRegistrationList")
    public PageDataInfo myRegistrationList(RetirementArticle retirementArticle)
    {
        retirementArticle.setUserId(SecurityUtils.getLoginUser().getUserId());
        if (!isAdmin()){
            retirementArticle.setDept(SecurityUtils.getLoginUser().getDeptId().toString());
        }
        // 获取分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        startPage();
        List<RetirementArticle> list = retirementArticleService.selectCollectList(retirementArticle);
        // 使用扩展的分页信息
        return new PageDataInfo(list, new PageInfo(list).getTotal(), pageNum, pageSize);
    }

    /**
     *  修改密码
     */
    @PostMapping(value = "/updatePass")
    public AjaxResult updateAvatar(@RequestBody Map<String, String> params)
    {
        String newPassword = params.get("newPassword");
        String code = params.get("code");
        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUserId();
        // 判断验证码是否正确
        if (loginService.validateSmsCode(loginUser.getUsername(), code)) {
            newPassword = SecurityUtils.encryptPassword(newPassword);
            userService.resetUserPwd(userId, newPassword);
            return success();
        } else {
            return AjaxResult.error("验证码错误或已失效");
        }
    }


    /**
     * 发送手机验证码（修改手机号用）
     *
     * @param mobile 手机验证码登录信息
     * @return 结果
     */
    @PostMapping("/phoneSendSms")
    public AjaxResult phoneSendSms(String mobile) {
        //判断手机号是否修改了
        String userName = SecurityUtils.getLoginUser().getUser().getUserName();
        if (StringUtils.isNotEmpty(mobile) && !userName.equals(mobile)) {
            //如果手机号修改了 查询是否已经注册过
            SysUser users = userService.selectUserByPhonenumber(mobile);
            if (users!=null) {
                return error("手机号已被注册！");
            }
        }else{
            return error("手机号无变化");
        }
        Integer status = loginService.sendSms(mobile);
        if (status.equals(1)) {
            return AjaxResult.success("发送成功，请注意查收");
        } else {
            return AjaxResult.error("发送失败，稍后请重试");
        }
    }


    /**
     * 发送手机验证码(修改密码用)
     * @return 结果
     */
    @PostMapping("/passSendSms")
    public AjaxResult passSendSms() {
        //判断手机号是否获取到
        String userName = SecurityUtils.getLoginUser().getUser().getUserName();
        if (StringUtils.isNotEmpty(userName) ) {
            Integer status = loginService.sendSms(userName);
            if (status.equals(1)) {
                return AjaxResult.success("发送成功，请注意查收");
            } else {
                return AjaxResult.error("发送失败，稍后请重试");
            }
        }else{
            return AjaxResult.error("手机号获取失败！");
        }
    }


    /**
     *  验证码校验
     */
    @PostMapping(value = "/checkCode")
    public AjaxResult checkCode(@RequestBody LoginByTelephoneBody smsLoginBody)
    {
        String phonenumber = smsLoginBody.getPhone();
        String code = smsLoginBody.getCode();
        // 判断验证码是否正确
        if (loginService.validateSmsCode(phonenumber, code)) {
            return success();
        } else {
            return AjaxResult.error("验证码错误或已失效");
        }
    }


    /**
     *  修改个人信息
     */
    @PostMapping(value = "/updateInfo")
    public AjaxResult updateInfo(@RequestBody SysUser user)
    {
        if (user == null) {
            return error("修改失败,请联系管理员！");
        }
        if (user.getUserName() == null) {
            return error("手机号不可为空！");
        }
        //判断手机号是否修改了
        String userName = SecurityUtils.getLoginUser().getUser().getUserName();
        if (StringUtils.isNotEmpty(userName) && !userName.equals(user.getUserName())) {
            //如果手机号修改了 查询是否已经注册过
            SysUser users = userService.selectUserByPhonenumber(user.getUserName());
            if (users!=null) {
                return error("手机号已被注册！");
            }
        }
        //修改个人信息
        return success(userService.updateUserMinApp(user));
    }
}
